<template>
  <div>
    <el-card>
      <el-row class="head" type="flex" justify="space-between" align="middle">
        <el-button type="primary" class="elButton" @click="ADDdialogVisible">添加分类</el-button>
        <div style="margin-top: 15px;" class="right">
          <el-input v-model="query.title_contains" placeholder="请输入内容">
            <el-button slot="append" icon="el-icon-search" @click="btnSearch"/>-->
          </el-input>
        </div>
      </el-row>
      <el-table :data="list" border style="width: 100%">
        <el-table-column prop="image" label="图片" width="180">
          <template #default="obj">
            <img :src="obj.row.image" alt style="width:180px;height:120px">
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="180"/>
        <el-table-column prop="desc" label="介绍"/>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="primary" @click="editPermission(row.id)">编辑</el-button>
            <el-button type="danger" @click="deleteEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="hr"/>
      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          layout="prev, pager, next"
          :total="page.total"
          :page-size="page.size"
          :current-page="page.page"
          @current-change="changePage"
        />
      </el-row>
    </el-card>
    <el-dialog
      :title="tableData.id ? '编辑分类' : '新增分类'"
      width="30%"
      :visible.sync="dialogVisible"
      @close="btnCancel"
    >
      <el-form ref="perTableData" :model="tableData" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="tableData.title"/>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="tableData.desc"/>
        </el-form-item>
        <el-form-item label="封面" prop="image">
          <imageUpload ref="houseimage"/>
        </el-form-item>
        <!-- <img :src="tableData.image" alt> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" @click="btnOK">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getcategories,
  postCategories,
  delCategories,
  getcategory,
  editCategory,
  pgCategories
} from "@/api/categories";
// import imageUpload from "@/components/ImageUpload";
import imageUpload from "@/components/ImageUpload";
export default {
  components: {
    imageUpload
  },
  data() {
    return {
      dialogVisible: false,
      // 上传图片
      dialogImageUrl: "",
      list: [],
      tableData: {
        title: "",
        desc: "",
        image: ""
      },
      page: {
        page: 1, // 当前页码
        size: 2,
        total: 20 // 总数
      },
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        desc: [{ required: true, message: "描述不能为空", trigger: "blur" }]
      },
      // 分页参数
      query: {
        // 每页获取条数
        _limit: 2,
        // 第0条开始获取数据
        _start: 0,
        // 带值的参数
        title_contains: ""
      }
    };
  },
  created() {
    this.pgCategories();
  },
  methods: {
    async pgCategories() {
      this.query._limit = 999;
      const start = this.query._start;
      this.query._start = 0;
      const data = await pgCategories(this.query);
      // 总数的长度
      // 获取总数
      this.query._limit = this.page.size;
      this.query._start = start;
      const res = await pgCategories(this.query);
      this.list = res.data;
      const result = await getcategories();
      this.query._limit = this.page.size;
      this.query._start = start;
      this.page.total = result.data.length;
    },
    // 搜索
    async btnSearch() {
      this.query._start = 0;
      this.query._limit = this.page.size;
      this.page.page = 1;
      let res = 0;
      // 判断是否有title_contains参数
      if (this.query.title_contains) {
        this.query._limit = 9999;
        res = await pgCategories(this.query);
        this.page.total = res.data.length;
        this.query._limit = this.page.size;
        // 有参查询
        this.query._limit = 999;
        res = await pgCategories(this.query);
        this.page.total = res.data.length;
        this.query._limit = this.page.size;
        res = await pgCategories(this.query);
      } else {
        // 默认查询全部
        // 获取新的总数
        const result = await getcategories();
        this.page.total = result.data.length;
        res = await pgCategories(this.query);
      }
      this.list = res.data;
    },
    // 点分页的时候调用的参数;
    async changePage(newPage) {
      // 当前分页点击的页数
      console.log(157, newPage);
      this.page.page = newPage;
      // 从第几条获取数据
      this.query._start = (this.page.page - 1) * this.query._limit;
      // 获取结果
      const result = await pgCategories(this.query);
      // 绑定数据重新渲染页面
      this.list = result.data;
    },
    // 页面初始化的数据
    async getcategories() {
      const res = await getcategories();
      this.page.total = res.data.length;
      this.list = res.data;
    },
    // 新增
    ADDdialogVisible() {
      this.dialogVisible = true;
    },
    // 编辑
    async editPermission(id) {
      this.dialogVisible = true;
      const res = await getcategory(id);
      this.tableData = res.data;
      if (res.data.image) {
        this.$refs.houseimage.fileList = [
          { url: res.data.image, upload: true }
        ];
      }
    },
    // 删除
    async deleteEmployee(id) {
      try {
        await this.$confirm("确定要删除该数据吗？");
        await delCategories(id);
        // 判断当前数据是否删除完
        if (this.page.total % this.query._limit) {
          // 删除完当前页数据自动跳转到上一页
          this.query._start = this.query._start - this.query._limit;
          this.page.page--;
        }
        this.pgCategories();
        this.$message.success("删除成功");
      } catch (error) {
        console.log(error);
      }
    },
    btnOK() {
      this.$refs.perTableData
        .validate()
        .then(() => {
          const fileList = this.$refs.houseimage.fileList;
          if (this.tableData.id) {
            return editCategory(
              this.tableData,
              (this.tableData.image = fileList[0].url)
            );
          }
          return postCategories(
            this.tableData,
            (this.tableData.image = fileList[0].url)
          );
        })
        .then(() => {
          if (!this.tableData.id) {
            this.$message.success("新增成功");
            this.pgCategories();
            this.dialogVisible = false;
          } else {
            this.$message.success("修改成功");
            this.pgCategories();
            this.dialogVisible = false;
          }
        });
    },
    btnCancel() {
      this.tableData = {
        title: "",
        desc: "",
        image: ""
      };
      this.$refs.perTableData.resetFields();
      this.$refs.houseimage.fileList = [];
      this.dialogVisible = false;
    }
  }
};
</script>

<style>
.hr {
  margin-top: 25px;
  margin-bottom: 10px;
  height: 1px;
  background-color: #ccc;
}
.head {
  margin-bottom: 25px;
  border-bottom: 1px solid #ccc;
}
.right {
  line-height: 90px;
}
.el-card {
  margin: 20px;
}
.el-input-group {
  width: 400px;
}
</style>
